TOP

SQL GROUP BY

SQL GROUP BY Description

The GROUP BY statement groups rows with the same values ​​into summary rows, such as "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group a result set by one or more columns.


GROUP BY Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s)

Demonstration database

The following is a sample from the "Customers" ("Customers") table of the "Northwind" database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.5021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.5023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

SQL GROUP BY Examples

The following SQL statement lists the number of customers in each country:

Run SQLSELECT COUNT(CustomerID), Country 
FROM Customers 
GROUP BY Country

The following SQL statement lists the customers in each country, sorted from highest to lowest:

Run SQLSELECT COUNT(CustomerID), Country 
FROM Customers 
GROUP BY Country 
ORDER BY COUNT(CustomerID) DESC

Demonstration database

The following is a sample from the "Orders" ("Orders") table of the "Northwind" database:

ProductIDOrderIDCustomerIDEmployeeIDOrderDateShipperID
1102489051996-07-043
2102498161996-07-051
3102503441996-07-082
4102518431996-07-081
5102527641996-07-092

And the sample from the table "Shippers" ("Senders"):

ShipperIDShipperNamePhone
1Speedy Express(503) 555-9831
2United Package(503) 555-3199
3Federal Shipping(503) 555-9931

GROUP BY together with JOIN Example

The following SQL statement lists the number of orders sent by each sender:

Run SQLSELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders 
FROM Orders 
LEFT JOIN Shippers 
ON Orders.ShipperID = Shippers.ShipperID 
GROUP BY ShipperName